﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using LynxWebLog.Areas.Blogs.ViewModels;

namespace LynxWebLog.Areas.Blogs.Controllers
{
    [Authorize(Roles="BlogUser,BlogAdmin")]
    public class PostEntryController : Controller
    {

        private string _blogOwner;
        private string _blogName;
        private BlogSupport blogSupport;
        private HttpClient client;
        protected override void Initialize(RequestContext requestContext)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            ViewBag.CategoryDisplay = false;
            ViewBag.GoogleAdDisplay = false;
            base.Initialize(requestContext);
            this._blogOwner = this.ControllerContext.RouteData.Values["username"].ToString();
            this._blogName = this.ControllerContext.RouteData.Values["blogname"].ToString();
            ViewBag.LegacyBrowser = Request.UserAgent.Contains("iPad; CPU OS 5");
            this.blogSupport = new BlogSupport();
            client = ClientUtility.BlogAPIClient();
        }

        //
        // GET: /Blogs/PostData/
        public async Task<ActionResult> Index()
        {
            HttpResponseMessage resp = await client.GetAsync("api/PostData?$filter=blogid eq '" + _blogOwner + "_" + _blogName + "'");
            resp.EnsureSuccessStatusCode();
            List<PostData> lpd = (await resp.Content.ReadAsAsync<IEnumerable<PostData>>()).ToList();

            return View(lpd);
        }

        //
        // GET: /Blogs/PostData/Details/5
        public async Task<ActionResult> Details(int id)
        {
            ViewBag.BlogId = _blogOwner + "_" + _blogName;
            HttpResponseMessage resp = await client.GetAsync("api/PostData/" + id);
            resp.EnsureSuccessStatusCode();
            PostEntry pe = (new PostEntry(await resp.Content.ReadAsAsync<PostData>()));

            resp = await client.GetAsync("api/PostCategory/?$filter=postid eq " + id);
            resp.EnsureSuccessStatusCode();

            List<PostCategory> lpc = new List<PostCategory>();
            lpc = (await resp.Content.ReadAsAsync<IEnumerable<PostCategory>>()).ToList();
            List<string> pc = new List<string>();
            foreach (PostCategory item in lpc) {
                resp = await client.GetAsync("api/CategoryData/" + item.category);
                resp.EnsureSuccessStatusCode();
                CategoryData cd = await resp.Content.ReadAsAsync<CategoryData>();
                pc.Add(cd.title);
                pe.categoryString += cd.title + ", ";
            }
            pe.pd.categories = pc.ToArray();

            return View(pe);
        }

        //
        // GET: /Blogs/PostData/Create
        public ActionResult Create()
        {
            ViewBag.BlogId = _blogOwner + "_" + _blogName;
            ViewBag.License = CC_License.BuildLicenseFlds(string.Empty, this.HttpContext);
            return View();
        }

        //
        // POST: /Blogs/PostData/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> Create(PostEntry pe)
        {
            if (!string.IsNullOrEmpty(pe.dateCreatedString)) {
                pe.pd.dateCreated = DateTime.Parse(pe.dateCreatedString);
            }
            ViewBag.License = CC_License.BuildLicenseFlds(string.Empty, this.HttpContext);
            pe.pd.categories = pe.categoryString.Split(',').ToArray();
            if (ModelState.IsValid) {
                try {
                    MetaWebLogAPI mwApi = new MetaWebLogAPI();
                    int newPostId = await mwApi.NewPost(_blogOwner, string.Empty, _blogOwner + "_" + _blogName, new Post(pe.pd));

                    return RedirectToAction("Index");
                }
                catch {
                    return View(pe);
                }
            }
            return View();
        }

        //
        // GET: /Blogs/PostData/Edit/5
        public async Task<ActionResult> Edit(int id)
        {
            HttpResponseMessage resp = await client.GetAsync("api/PostData/" + id);
            resp.EnsureSuccessStatusCode();
            PostEntry pe = (new PostEntry(await resp.Content.ReadAsAsync<PostData>()));
            ViewBag.License = CC_License.BuildLicenseFlds(pe.pd.license, this.HttpContext);

            resp = await client.GetAsync("api/PostCategory/?$filter=postid eq " + id);
            resp.EnsureSuccessStatusCode();

            List<PostCategory> lpc = new List<PostCategory>();
            lpc = (await resp.Content.ReadAsAsync<IEnumerable<PostCategory>>()).ToList();
            List<string> pc = new List<string>();
            foreach (PostCategory item in lpc) {
                resp = await client.GetAsync("api/CategoryData/" + item.category);
                resp.EnsureSuccessStatusCode();
                CategoryData cd = await resp.Content.ReadAsAsync<CategoryData>();
                pc.Add(cd.title);
                pe.categoryString += cd.title + ", ";
            }
            pe.pd.categories = pc.ToArray();

            return View(pe);
        }

        //
        // POST: /Blogs/PostData/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> Edit(PostEntry pe)
        {
            ViewBag.License = CC_License.BuildLicenseFlds(pe.pd.license, this.HttpContext);
            if (!string.IsNullOrEmpty(pe.dateCreatedString)) {
                pe.pd.dateCreated = DateTime.Parse(pe.dateCreatedString);
            }
            if (!string.IsNullOrEmpty(pe.categoryString)) {
                pe.pd.categories = pe.categoryString.Split(',').ToArray();
            }
            try
            {
                MetaWebLogAPI mwApi = new MetaWebLogAPI();
                await mwApi.EditPost(_blogOwner, string.Empty, new Post(pe.pd));

                return RedirectToAction("Index");
            }
            catch
            {
                return View(pe);
            }
        }

        //
        // GET: /Blogs/PostData/Delete/5
        public async Task<ActionResult> Delete(int id)
        {
            HttpResponseMessage resp = await client.GetAsync("api/PostData/" + id);
            resp.EnsureSuccessStatusCode();
            PostEntry pe = (new PostEntry(await resp.Content.ReadAsAsync<PostData>()));

            return View(pe);
        }

        //
        // POST: /Blogs/PostData/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> DeleteConfirmed(int postid)
        {
            try
            {
                MetaWebLogAPI mwApi = new MetaWebLogAPI();
                await mwApi.DeletePost(_blogOwner, string.Empty, postid);

                return RedirectToAction("Index");
            }
            catch (SystemException ex) {
                Debug.Print(ex.Message);
                return RedirectToAction("Delete");
            }
        }
    }
}
